package org.gary.news.dao.impl;

import static lengreen.util.BuildQuery.buildNativeTableName;

import java.sql.SQLException;

import javax.annotation.Resource;

import org.gary.news.dao.NewsDao;
import org.gary.news.model.News;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;

/**
 * 
 * @author lengreen,Gary
 *
 */
@Component("newsDao")
public class NewsDaoImpl implements NewsDao {
	private HibernateTemplate hibernateTemplate;
	private String hql;
	
	@Override
	public <T> T loadImages(int newsId) {
		setHql("select news.images from " + News.class.getName()
				+ " news where news.id=" + newsId);
		T t = hibernateTemplate.execute(new HibernateCallback<T>() {

			@SuppressWarnings("unchecked")
			@Override
			public T doInHibernate(Session session) throws HibernateException,
					SQLException {
				Query q = session.createQuery(getHql());
				return (T) q.list();
			}
		});
		return t;
	}

	@Resource
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	public void setHql(String hql) {
		this.hql = hql;
	}

	public String getHql() {
		return hql;
	}

	@Override
	public void addBrowse(int id) {
		setHql("update " + buildNativeTableName(News.class)
				+ " set viewCount = viewCount+1 where id = "+id);
		SQLQuery sqlquery = hibernateTemplate.getSessionFactory().openSession().createSQLQuery(getHql());
		sqlquery.executeUpdate();		
	}

}
